package com.zr.controller;

import com.github.pagehelper.PageInfo;
import com.zr.pojo.Student;
import com.zr.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentService studentService;
    @RequestMapping("/to_add")
    public String to_add(){
        return "add";
    }
    @RequestMapping("/add")
    public String add(HttpServletRequest request, Student student , MultipartFile upload){
    String path=request.getSession().getServletContext().getRealPath("/upload/");
    File file=new File(path);
    if(!file.exists()){
        file.mkdirs();
    }
        String filename = upload.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString().replace("-", "")+filename;
        try {
            upload.transferTo(new File(path,filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        studentService.add(student);
//        for (Object o : new ArrayList<>()) {
//
//        }
        return "redirect:/student/list";
    }
    @RequestMapping("/to_list")
    public String to_list(){
        return "list";
    }
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum, Model model){
        PageInfo<Student> studentPageInfo = studentService.selectByPage(pageNum, 5);
        model.addAttribute("pageInfo",studentPageInfo);
        return "list";
    }
    @RequestMapping("/to_find")
    public String to_find(){
        return "find";
    }

    @RequestMapping(value = "/findOne",method = RequestMethod.POST)
   @ResponseBody

    public Student to_find(@RequestBody Student student){
        System.out.println(student);
        Student student1 = studentService.selectOne(student);
        System.out.println(student1.getSno());
        System.out.println(student1.getSname());
        System.out.println(student1.getBirthday());
        return student1;
    }

    @RequestMapping("/to_redisList")
    public String to_redisList(){
        return "redisList";
    }
//    @RequestMapping(value = "/redisTest1",produces = "text/html;charset=UTF-8")
@RequestMapping(value = "/redisTest1",produces = "application/json;charset=UTF-8")
//    @PostMapping("/redisTest1")
    @ResponseBody
    public String redisTest1(){


        return studentService.selectAll();
    }


}
